package core

import (
	"fmt"
	"gin-backend/model"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"os"
)

func InitDatabase() {
	DB = Gorm()
}

func Gorm() *gorm.DB {
	switch CONF.Database.Type {
	case "mysql":
		return GormMySQL()
	case "sqlite":
		return GormSQLite()
	default:
		return GormSQLite()
	}
}

func AutoMigrateTables() {
	err := DB.AutoMigrate(
		model.SysUser{},
		/*		model.SysAuthority{},
				model.SysApi{},
				model.SysBaseMenu{},
				model.SysBaseMenuParameter{},
				model.JwtBlacklist{},
				model.SysDictionary{},
				model.SysDictionaryDetail{},
		*/)
	if err != nil {
		fmt.Println("register table failed", err)
		os.Exit(1)
	}
}

func GormMySQL() *gorm.DB {
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s", CONF.Database.Username, CONF.Database.Password,
		CONF.Database.Host, CONF.Database.Dbname, CONF.Database.Conf)
	mysql_config := mysql.Config{
		DSN:                       dsn,
		DefaultStringSize:         191,
		DisableDatetimePrecision:  true,
		DontSupportRenameIndex:    true,
		DontSupportRenameColumn:   true,
		SkipInitializeWithVersion: false,
	}
	if db, err := gorm.Open(mysql.New(mysql_config), &gorm.Config{}); err != nil {
		os.Exit(1)
		return nil
	} else {
		return db
	}
}

func GormSQLite() *gorm.DB {
	dsn := fmt.Sprintf("%s", CONF.Database.Dbname)
	if db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{}); err != nil {
		os.Exit(1)
		return nil
	} else {
		return db
	}
}
